'use strict';

const { Service } = require('egg');

class UserAccessService extends Service {
  async login(payload) {
    const { ctx, service } = this;
    // 用户名
    const user = await this.service.user.findByMobile(payload.mobile);
    if (!user) {
      ctx.throw(404, 'user not found');
    }
    const verifyPsw = await ctx.compare(payload.password, user.password);
    if (!verifyPsw) {
      ctx.throw(404, 'user password is error');
    }

    // 生成令牌
    return {
      token: await service.actionToken.apply(user._id),
    };
  }

  // eslint-disable-next-line no-empty-function
  async logout() {}

  async current(_id) {
    const { ctx, service } = this;
    // const _id = ctx.app.state.user.data._id;
    const user = await service.user.find(_id);
    if (!user) {
      ctx.throw(404, 'user not found');
    }
    user.password = 'haha'; // 用户密码不能给别人

    return user;
  }
}

module.exports = UserAccessService;
